import routes, { asyncRouteMap } from '@/router/routes';
import getMenuRoutes from '@/router/permission';

function toSortedList(list) {
  list.forEach((temp) => {
    const l = temp;
    if (l.children) {
      l.children = toSortedList(l.children);
    }
  });
  return list.toSorted((a, b) => a.meta.order - b.meta.order);
}

function filterMenu(list) {
  return list.filter((temp) => {
    const r = temp;
    if (r.meta?.menu === 'home') {
      if (r.children) r.children = filterMenu(r.children);
      return true;
    }
    return false;
  });
}

export default {
  namespaced: true,
  getters: {
    asyncRoutes(state, getters, rootState) {
      return getMenuRoutes(rootState.userInfo.role, asyncRouteMap);
    },
    menus(state, getters) {
      const result = getters.asyncRoutes
        .concat(routes);
      return toSortedList(filterMenu(result));
    },
  },
};
